package com.th.supcom.pds.impl.service.jms;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class JmsQueueMessegeListener implements MessageListener, BeanFactoryAware
{
    private BeanFactory m_beanFactory;
    private static final Logger LOGGER = LoggerFactory.getLogger (MessageListener.class);

    @SuppressWarnings ("unchecked")
    @Override
    public void onMessage (Message arg0)
    {
        ObjectMessage objectMessage = (ObjectMessage) arg0;
        try
        {
            LOGGER.info ("jms接受消息:{}", new Object[]
            { objectMessage.getObject () });
            Map <String, String> dataKayMap = (Map <String, String>) objectMessage.getObject ();
            for (Entry <String, String> entry : dataKayMap.entrySet ())
            {
                LOGGER.info ("jms接受消息beanId：{}，jms接受消息执行参数：{}", new Object[]
                { entry.getKey (), entry.getValue () });
                String[] keys = entry.getKey ().split ("\\.");
                Object classBean = m_beanFactory.getBean (keys[0]);
                String methdName = keys[1];
                Method method = classBean.getClass ().getMethod (methdName, String.class);
                method.invoke (classBean, entry.getValue ());
            }
        }
        catch (JMSException e)
        {
            throw new RuntimeException ("jms接受器解析消息异常JMSException", e);
        }
        catch (NoSuchMethodException e)
        {
            throw new RuntimeException ("jms接受器解析消息异常NoSuchMethodException", e);
        }
        catch (Exception e)
        {
            throw new RuntimeException ("jms接受器解析消息异常Exception", e);
        }

    }

    @Override
    public void setBeanFactory (BeanFactory beanFactory) throws BeansException
    {
        m_beanFactory = beanFactory;
    }
}
